const { Controller } = require("egg");
class TopicController extends Controller {
  async list() {
    const { topicId } = this.ctx.query;
    if (!topicId) {
      return this.ctx.helper.error("参数异常：缺少topicId");
    }
    const result = await this.service.topic.id(topicId);
    if (!result) {
      return this.ctx.helper.error("该专题不存在");
    }

    try {
      const result = await this.service.topicTeacher.list(topicId);
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(`获取讲师列表失败：${error.message}`);
    }
  }

  async create() {
    const { ctx } = this;
    const { topicId, name, avatar, title, desc } = ctx.request.body;

    if (!topicId || !name || !avatar) {
      return this.ctx.helper.error("讲师姓名、头像或topicId不能为空");
    }
    try {
      const topic = await this.service.topic.id(topicId);
      if (!topic) {
        return this.ctx.helper.error("该专题不存在");
      }
      const params = {
        topicId,
        name,
        avatar,
        title,
        desc
      }
      const result = await ctx.service.topicTeacher.create(params);
      this.ctx.helper.success(result, "讲师创建成功");
    } catch (error) {
      this.ctx.helper.error("创建讲师失败：" + error.message);
    }
  }

  async delete() {
    const { id } = this.ctx.request.body;
    if (!id) {
      return this.ctx.helper.error("参数异常：缺少讲师ID");
    }
    try {
      const deleted = await this.service.topicTeacher.delete(id);
      if (!deleted) {
        return this.ctx.helper.error("讲师不存在或删除失败");
      }
      this.ctx.helper.success(deleted, "讲师删除成功");
    } catch (error) {
      this.ctx.helper.error("删除讲师失败：" + error.message);
    }
  }


  async update() {
    const { id, ...updateData } = this.ctx.request.body;
    if (!id) {
      return this.ctx.helper.error("参数异常：缺少讲师ID");
    }
    try {
      const updated = await this.service.topicTeacher.update(id, updateData);
      if (!updated) {
        return this.ctx.helper.error("讲师不存在或更新失败");
      }
      this.ctx.helper.success(updated, "讲师信息更新成功");
    } catch (error) {
      this.ctx.helper.error("更新讲师信息失败：" + error.message);
    }
  }

}

module.exports = TopicController;
